/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  TouchableHighlight,
  ToolbarAndroid,
  Dimensions,
  ListView,
  RefreshControl,
  DeviceEventEmitter,
  Platform,
  PixelRatio
} from 'react-native';

import {CachedImageBackground} from "react-native-img-cache";

import Common from '../../../component/common';
import ScreenUtils from '../../../component/ScreenUtils';
import Toast from 'react-native-root-toast';

import Detail from '../../home/detail';
import VarietySearch from '../../search/varietySearch';

export default class varietyItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
  		dataSource: new ListView.DataSource({
          	rowHasChanged: (row1, row2) => row1 !== row2,
        	}),
  		showDeleteButton: this.props.showDeleteButton,
  		sectionTitle: this.props.data.typeName,
  		rows :this.props.data.list,
  		deleteStatus: false,
  		classType:this.props.classType,
  		showTitle:this.props.showTitle,
      deleteArr:[],
      dataLength:this.props.data.list.length
		
  	};
    this.selectArr=[];
    this.openScroll=[]
  }
  componentWillReceiveProps(nextProps){
    
  	if(nextProps.refreshType == parseInt(this.state.classType) && parseInt(nextProps.classType) == parseInt(this.state.classType) && nextProps.data.list!=this.state.rows){
  		this.setState({
  			dataSource: this.state.dataSource.cloneWithRows(nextProps.data.list),
		  	rows:nextProps.data.list,
		  	dataLength:nextProps.data.list.length,
		})
  	}
    if(this.openScroll.length>0){
      this.openScroll.map((item,key)=>{
          item.scrollTo({ x: 0, y: 0, animated: false });
          this.openScroll=[]
      })
    }
  }
  
  componentWillUnmount() {
   
  }
  componentDidMount(){
  	if(this.props.data.length < this.props.totalPage ){
  		this.setState({
  			showPagation:true,
  		})
  	}
  	this.setState({
  		dataSource: this.state.dataSource.cloneWithRows(this.state.rows),
  	})
  }
  handleDelete(rowIndex,entityId,target){
  	let formData = new FormData();
	formData.append("entityId",entityId);
	formData.append("userToken",this.props.userToken);
	Common.fetchData("POST", "/userCenter/collect/delete", formData, (responseData) => {
    let isShowTitle=this.state.dataLength;
    let showTitle = isShowTitle==1 ? false :true;
    /*if(isShowTitle==1){
      DeviceEventEmitter.emit("noData",null);
    }*/
		this.selectArr.push(entityId);
      this.setState({
        deleteArr:this.selectArr,
        dataLength:isShowTitle-1,
        showTitle:showTitle
      });
      target.scrollTo({x: 0, y: 0, animated: false});
		// let arr= JSON.parse(JSON.stringify(this.state.rows));
		// arr.splice(rowIndex,1);

		
		//DeviceEventEmitter.emit("dealCollection",this.state.classType);
		
		
		// if(this.state.dataLength>0 && this.state.dataLength-1 != rowIndex){
		// 	target.scrollTo({x: 0, y: 0, animated: false});
		// }
		
		Toast.show("删除成功",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	},() => {
		Toast.show("删除失败",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	},() => {
		Toast.show("网络错误",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	});
  }
  render(){
    
  	let propDataLength = this.state.rows.length;
  	if(propDataLength===0){
  		return null;
  	}else{
      let marginStyle = this.state.dataLength>0 ? {
       
      } : {};
		return(
		<View style={styles.collectionVariety}>
      			{
      				this.state.showTitle?　
      					<Text style={styles.collectionCategory}>
      						{this.state.sectionTitle}
      						{
      							this.props.totalPage ? <Text>({String(this.props.totalPage)})</Text> :null
      						}
      					</Text>　: null
      			}
      			<View style={[styles.Item,marginStyle]}>
              {
                this.state.rows.map((item,key)=>{
                    return this.renderVariety(item,key);
                })
              }
    					{
    						this.props.pagation ?
    							<TouchableOpacity style={styles.showMore}  onPress={() => Common.onForward(this.props.chageThis,VarietySearch,VarietySearch,this.props.keywords,this.props.type)}>
    								<Image source = {require('../../../images/toBottom.png')}/>
    								<Text style={{marginLeft:10,fontSize:ScreenUtils.scaleSize(20),}}>展开</Text>
    							</TouchableOpacity> :(
                    this.state.showDeleteButton ? null : <View style={styles.seperatorCell}></View>
                  )
    					}
				    </View>
		</View>
		)  		
  	}
  }
  _renderCellSeparator(sectionID, rowID, adjacentRowHighlighted){
  	return (
  		<View style={styles.cellSeparator}></View>
  	)
  }


  updown = (data) =>{
    var updown = {};
    // var data = data?parseInt(data):0;
    if(data > 0){
      updown.change = data;
      updown.icon = require('../../../images/up.png');
    }else if(data < 0){
      updown.change = -data;
      updown.icon = require('../../../images/down.png');
    }else{
      updown.change = "";
      updown.icon = require('../../../images/still.png');
    }
    return updown;
  };
  
 showDeleteButton(ev,target){
  	if(this.startLocation>this.moveLocation){
  		target.scrollToEnd({animated: true});
      this.openScroll.push(target);
  	}else{
  		target.scrollTo({x:0,y:0,animated: true});
  	}
  }
 
  renderVariety(data,rowID) {
  	var _scrollView: ScrollView;
  	var updown = this.updown(data.rankingChanged);
  	var mydata = Common.keyWordHighlight(data.title);
    var Vheight = ScreenUtils.scaleSize(200);
    var vMarginBottom=ScreenUtils.scaleSize(14);
    this.state.deleteArr.map((item,key)=>{
      if(item==data.id){
        Vheight=0;
        vMarginBottom=0;
      }
    })
    return (
    <ScrollView
      	horizontal = {true}
      	showsHorizontalScrollIndicator = {false}
      	ref={(scrollView) => { _scrollView = scrollView; }}
      	contentContainerStyle={{marginBottom:vMarginBottom,height:Vheight,overflow:"hidden"}}
      	onTouchStart={(event)=>{
      		this.startLocation=event.nativeEvent.pageX
      	}}
      	onTouchMove={(event)=>{
      		this.moveLocation=event.nativeEvent.pageX
      	}}
      	onScrollEndDrag={(event)=>{
      		 this.showDeleteButton(event,_scrollView);
      	}}
        style={{}}
        key={rowID}
        bounces={false}
    >
      <TouchableHighlight underlayColor="#fafafa" delayPressIn={100} style ={[styles.vItemContainer,{height:Vheight}]} 
      onPress={() => Common.onForward(this.props.chageThis,Detail,data.type||this.props.classType,data.id)}>
        <View style={{flex:1,flexDirection:"row"}}>
          <View style={styles.vDescription}>
      			<View style={[styles.vDesImgWrap,{
      				marginLeft:ScreenUtils.scaleSize(20),
      			}]}>
      				{
      					data.mainPicPath ? 
      						<CachedImageBackground 
      							style={styles.vDesImg} 
      							source={{uri: data.mainPicPath }}
      						/>	: <View style={[styles.vDesImgWrap,{borderWidth:1,borderColor:"#ededed"}]}><Text style={styles.noImg}>暂无图片</Text></View>
      				}
      			</View>
    			  <View style={styles.vDesInfo}>
      				<Text style={styles.vDesTitle} numberOfLines ={2}>
      					{
      						!this.props.search ? <Text>{data.title}</Text>:
      						<Text>
      						{
      						    mydata.map((item,i)=>{
      						        if(item.hightLight){
      						          	return(
      						          		<Text key={i} style={{color:"red"}}>{item.data}</Text>
      						          	)
      						        }else{
      						          	return(
      						          		<Text key={i}>{item.data}</Text>
      						          	)
      						        }
      						    })
      					    }
      						</Text>
      					}
      				
      				</Text>
      				{
      					data.programTypeList ?
      						<View style={styles.vDesCategory}>
      							{
      								 data.programTypeList.map((item,i)=>{
      									return <View style={styles.vDes}><Text key={i} style={styles.vDesCategoryItem}>{item.title}</Text></View>
      								})
      							}
      						</View> : null
      				}
    				
      				<View style={styles.varietyContent}>
      					{
      						typeof(data.ranking)!=='undefined'?
      						<Text style={styles.vBillBoard}>榜单 <Text style={{color:"#ff5151",}}>No.{String(data.ranking)}</Text></Text> : null
      					}
      					
      					{
      						typeof(data.rankingChanged)!=='undefined' ? <Image style={{marginLeft:5,}} source = {updown.icon}/> : null
      					}
      				</View>
    			  </View>
        	</View>
        	<View style={styles.vIndex}>
        		<Text style={styles.vIndexTitle}>报道指数</Text>
        		<Text style={styles.vIndexNum}>{data.indexNumber ? String(parseFloat(data.indexNumber).toFixed(1)):"0.0"}</Text>
        	</View>
        </View>
      </TouchableHighlight>
	    {
	      	this.state.showDeleteButton ?
		      (
		      	<TouchableOpacity 
		      		style={styles.deleteWrap} 
		      		onPress={()=>{
		      			this.handleDelete(rowID,data.id,_scrollView)
		      			}
		      		}
		      	>
			      <Text style={styles.deleteText}>删除</Text>
			    </TouchableOpacity>
		      ):null
	    }
    </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  cellSeparator:{
  	flex:1,
  	height:ScreenUtils.scaleSize(100),
  },
  vItemContainer:{
    width:Dimensions.get('window').width,
  	backgroundColor:"#fff",
  	flexDirection:"row",
  	height:ScreenUtils.scaleSize(200),
  	borderBottomWidth:1,
    borderTopWidth:1,
  	borderColor:"#ebebeb",
  	justifyContent:"center",
  	paddingLeft:ScreenUtils.scaleSize(30),
  	paddingRight:ScreenUtils.scaleSize(26),
  },
  vDescription:{
  	flex:1,
  	height:ScreenUtils.scaleSize(200),
  	flexDirection:"row",
  	alignItems:"center",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#939393",
  	paddingTop:ScreenUtils.scaleSize(14),
    paddingBottom:ScreenUtils.scaleSize(14),
  },
  vDesImgWrap:{
  	width:ScreenUtils.scaleSize(110),
  	height:ScreenUtils.scaleSize(152),
  	justifyContent:"center",
  	alignItems:"center",
  },
  noImg:{
  	color:"#ededed",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  vDesImg:{
  	width:ScreenUtils.scaleSize(110),
  	height:ScreenUtils.scaleSize(152),
  },
  vDesInfo:{
  	flex:1,
  	height:ScreenUtils.scaleSize(152),
  	flexDirection:"column",
  	justifyContent:"space-around",
  	paddingLeft:ScreenUtils.scaleSize(26),
  },
  vDesTitle:{
  	fontSize:ScreenUtils.scaleSize(34),
  	color:"#000",
  },
  vDesCategory:{
  	flexDirection:"row",
  },
  vDes:{
  	borderWidth:1,
  	borderColor:"#ff5050",
  	borderRadius:2,
  	marginRight:5,
    paddingHorizontal: 5,
  },
  vDesCategoryItem:{
  	fontSize:ScreenUtils.scaleSize(16),
    
  	color:"#ff4545",
  },
  vBillBoard:{
  	fontSize:ScreenUtils.scaleSize(20),
  	color:"#000",
  },
  vIndex:{
  	width:ScreenUtils.scaleSize(200),
  	alignItems:"flex-end",
  	justifyContent:"center",
  	paddingRight:ScreenUtils.scaleSize(20),
  },
  vIndexTitle:{
  	color:"#d7d7d7",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  varietyContent:{
  	flexDirection:"row",
  	alignItems:"center",
  },
  vIndexNum:{
  	fontSize:ScreenUtils.scaleSize(60),
  	color:"#ff4545",
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
  Item:{
  	
  	borderColor:"#ededed",
  },
  showMore:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(78),
  	backgroundColor:'#fff',
  	borderBottomWidth:1,
  	borderColor:'#ebebeb',
  	flexDirection:"row",
  	marginTop:-ScreenUtils.scaleSize(14),
  },
  seperatorCell:{
  	backgroundColor:"#f60",
  	marginTop:-ScreenUtils.scaleSize(14),
  	zIndex:-5,
  }
});